<template>
  <LoginHeader>联合登录</LoginHeader>
  <section class="container">
    <nav class="tab">
      <a
        href="javascript:;"
        @click="hasAccount = true"
        :class="{ active: hasAccount }"
      >
        <i class="iconfont icon-bind" />
        <span>已有小兔鲜账号，请绑定手机</span>
      </a>
      <a
        href="javascript:;"
        @click="hasAccount = false"
        :class="{ active: !hasAccount }"
      >
        <i class="iconfont icon-edit" />
        <span>没有小兔鲜账号，请完善资料</span>
      </a>
    </nav>
    <!-- 有账号 -->
    <div class="tab-content" v-if="hasAccount">
      <CallbackBind :unionId='unionId'/>
    </div>
    <!-- 没有账号 -->
    <div class="tab-content" v-else>
      <CallbackPatch  :unionId='unionId'/>
    </div>
  </section>
  <LoginFooter />
</template>

<script>
import LoginHeader from './components/login-header'
import LoginFooter from './components/login-footer'
import CallbackBind from './components/callback-bind'
import CallbackPatch from './components/callback-patch'
import { userQQLogin } from '@/api/user'

import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

import { message } from '@/components/Message/index.js'

export default {
  name: 'PageCallback',
  components: { LoginHeader, LoginFooter, CallbackBind, CallbackPatch },
  setup () {
    // qq用户标识
    const unionId = ref()

    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    // 是否有账号
    const hasAccount = ref(false)

    /**
     * 1.  检查QQ是否授权登录:window.qc.Login.check()//二次确认，防止成功的token是伪造的
     * 2.  如果授权登录获取openId:window.qc.Login.getMe((openId)=>{})
     * 3.  使用openId获取后台用户数据存vuex
     * 4.  跳转首页
     */

    if (window.qc.Login.check()) {
    //   console.log('授权成功')
      window.qc.Login.getMe(async (openId) => {
        // console.log('用户标识', openId)
        unionId.value = openId
        try {
          // 有小兔子账号已绑定
          const { result } = await userQQLogin(openId)

          // 登陆成功存储用户信息
          await store.commit('user/setProfile', result)
          // 是否带有401的页面
          router.replace(route.query.redirect || '/')
          message({ type: 'success', text: 'qq登陆成功' })
        } catch (error) {
          message({ type: 'success', text: 'qq登陆失败' })

        //   console.log(error)
        }
      })
    }

    return {
      hasAccount, unionId
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 25px 0;
}
.tab {
  background: #fff;
  height: 80px;
  padding-top: 40px;
  font-size: 18px;
  text-align: center;
  a {
    color: #666;
    display: inline-block;
    width: 350px;
    line-height: 40px;
    border-bottom: 2px solid #e4e4e4;
    i {
      font-size: 22px;
      vertical-align: middle;
    }
    span {
      vertical-align: middle;
      margin-left: 4px;
    }
    &.active {
      color: @xtxColor;
      border-color: @xtxColor;
    }
  }
}
.tab-content {
  min-height: 600px;
  background: #fff;
}
</style>
